package model

import (
	"gorm.io/gorm"
	"seckill-srv/basic/config"
	"time"
)

type Order struct {
	gorm.Model
	UserId          int       `json:"user_id" gorm:"type:int;comment:'用户id'"`
	ActivityId      int       `json:"activity_id" gorm:"type:int;comment:'活动id'"`
	OrderSn         string    `json:"order_sn" gorm:"type:varchar(50);comment:'订单编号'"`
	OrderPrice      float32   `json:"order_price" gorm:"type:decimal(10,2);comment:'订单金额'"`
	OrderNum        int       `json:"order_num" gorm:"type:int;comment:'订单数量'"`
	OrderStatus     int       `json:"order_status" gorm:"type:int;comment:'订单状态 1-待支付 2-已支付 3-已取消'"`
	PayDurationTime int       `json:"pay_duration_time" gorm:"type:int;comment:'支付超时时间'"`
	PayMothed       int       `json:"pay_mothed" gorm:"type:int;comment:'支付方式 1-支付宝 2-微信'"`
	PayStatus       int       `json:"pay_status" gorm:"type:int;comment:'支付状态 1-待支付 2-已支付 3-支付超时 4-支付失败'"`
	PayTime         time.Time `json:"pay_time" gorm:"type:datetime;default:null;comment:'支付时间'"`
}

func (o *Order) TableName() string {
	return "order"
}

// 添加订单
func (o *Order) AddOrder() error {
	return config.DB.Create(&o).Error
}

// 查询订单列表
func (o *Order) GetOrderList() (orders []*Order, err error) {
	err = config.DB.Find(&orders).Error
	return
}

// 根据订单编号查询订单
func (o *Order) GetOrderBySn(orderSn string) error {
	return config.DB.Where("order_sn = ?", orderSn).Limit(1).Find(&o).Error
}

// 根据userId和activityId查询订单
func (o *Order) GetOrderInfo(userId, activityId int) error {
	return config.DB.Where("user_id = ? and activity_id = ?", userId, activityId).Limit(1).Find(&o).Error
}

// 更新订单
func (o *Order) UpdateOrderStatus(tx *gorm.DB, orderSn string) error {
	return tx.Model(&Order{}).Where("order_sn = ?", orderSn).Update("pay_status", o.PayStatus).Error
}

// 删除订单
func (o *Order) DelOrder(tx *gorm.DB, orderSn string) error {
	return tx.Model(&o).Where("order_sn = ?", orderSn).Delete(&o).Error
}
